using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Core;

namespace Forum.Business
{
    public class SectionAdd : ForumUserControl,
        IReplyConverter<GroupReply, GetListOperation>
    {
        protected ValuedTextBox subjectTextBox;
        protected ValuedCheckBox enabledCheckBox;
        protected ValuedDropDownList groupDropDownList;
        protected ResourceButton saveButton;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            if (!IsPostBack)
            {
                requestBinders.Add(RequestHelper.BuildGetGroupListRequest(this));
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!ValidatePermission(PermissionType.SectionAdmin))
            {
                throw new Exception("Access denied.");
            }
            saveButton.Click += new EventHandler(SaveSection);
        }

        private void BindData(GroupReply reply)
        {
            if (groupDropDownList != null)
            {
                groupDropDownList.DataSource = reply.EntityList;
                groupDropDownList.DataTextField = "Subject";
                groupDropDownList.DataValueField = "EntityId";
                groupDropDownList.DataBind();

                int? groupId = UrlManager.Instance.GetParameterValue<int?>(ForumParameterName.GroupId.ToString().ToLower());
                if (groupId.HasValue)
                {
                    groupDropDownList.Value = groupId.Value.ToString();
                }
            }
        }
        private void SaveSection(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(groupDropDownList.Value))
            {
                return;
            }

            Section section = new Section();

            section.Subject.Value = subjectTextBox.Value;
            section.Enabled.Value = enabledCheckBox.Checked ? 1 : 0;
            section.GroupId.Value = int.Parse(groupDropDownList.Value);

            BusinessManager.CreateSection(section);
            Page.Response.Redirect(UrlManager.Instance.FormatUrl("section_list", int.Parse(groupDropDownList.Value)));
        }

        #region IReplyConverter<GroupReply,GetListOperation> Members

        public void ConvertReply(GroupReply reply, GetListOperation operation)
        {
            if (reply != null)
            {
                BindData(reply);
            }
        }

        #endregion
    }
}